package com.cunshe.service;

import com.cunshe.common.FileUtil;
import com.cunshe.dao.HomeBannerDao;
import com.cunshe.domain.HomeBanner;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 首页图片
 * @author 
 */
@Service
public class HomeBannerService {

    @Autowired
    private HomeBannerDao homeBannerDao;

    @Transactional(rollbackFor = Exception.class)
    public int insert(HomeBanner record) {
        return homeBannerDao.insert(record);
    }

    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        HomeBanner homeBanner = get(id);
        if(homeBanner == null){
            return 0;
        }
        int delete = homeBannerDao.delete(id);

        FileUtil.deleteFile(homeBanner.getImageUrl());

        return delete;
    }

    @Transactional(rollbackFor = Exception.class)
    public int update(HomeBanner record) {
        HomeBanner homeBanner = get(record.getId());
        if(homeBanner == null){
            return 0;
        }

        int update = homeBannerDao.update(record);
        if(!record.getImageUrl().equals(homeBanner.getImageUrl())){
            FileUtil.deleteFile(homeBanner.getImageUrl());
        }
        return update;
    }

    public HomeBanner get(Long id) {
        if(id == null){
            return null;
        }
        return list(HomeBanner.builder().id(id).build())
                .stream()
                .findFirst()
                .orElse(null);
    }

    public List<HomeBanner> all() {
        PageHelper.orderBy(" sort_num DESC ");
        return homeBannerDao.list(null);
    }

    public List<HomeBanner> list(HomeBanner record) {
        return homeBannerDao.list(record);
    }

}